package com.cdie.myschool.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cdie.myschool.common.R;
import com.cdie.myschool.domain.dto.ScienceDTO;
import com.cdie.myschool.domain.entity.*;
import com.cdie.myschool.domain.vo.AbilityTagVO;
import com.cdie.myschool.domain.vo.ScienceVO;
import com.cdie.myschool.domain.vo.TeacherStartupPageVO;
import com.cdie.myschool.domain.vo.TeacherVO;
import com.cdie.myschool.mapper.TeacherTermReportMapper.*;
import com.cdie.myschool.service.TeacherTermReportService;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 明祺奇-199000331
 * @date 2022/10/5 - 9:41
 */
@Service
public class TeacherTermReportServiceImpl implements TeacherTermReportService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private TeacherMapper teacherMapper;

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private PapersMapper papersMapper;

    @Autowired
    private EduReformMapper eduReformMapper;

    @Autowired
    private AbilityTagMapper abilityTagMapper;

    /**
     * @author 明祺奇
     * 导入教师表
     */
    @Override
    @DS("master")
    public void insertTeacherDataIntoTeacher(List<TeacherOld> teacherDataList) {
        if (teacherDataList.size() == 0){
            return;
        }
        Logger logger = null;
        StringBuilder sql = new StringBuilder();
        sql.append("insert into teacher(teacher_name,teacher_sex,teacher_id_card,teacher_current_status,teacher_code,department_code,teacher_job,teacher_part_time_job,timestamp,enter_date,admission_date) values ");
        sql.append("('")
                .append(teacherDataList.get(0).getXM()).append("',")
                .append(teacherDataList.get(0).getXBM()).append(",'")
                .append(teacherDataList.get(0).getSFZJH()).append("','")
                .append(teacherDataList.get(0).getJZGDQZTM()).append("','")
                .append(teacherDataList.get(0).getGH()).append("','")
                .append(teacherDataList.get(0).getSZDWBM()).append("','")
                .append(teacherDataList.get(0).getGW()).append("','")
                .append(teacherDataList.get(0).getJRZW()).append("','")
                .append(teacherDataList.get(0).getTSTAMP()).append("','")
                .append(teacherDataList.get(0).getLXRQ()).append("','")
                .append(teacherDataList.get(0).getCJGZNY())
                .append("')")
        ;
        for (int i = 1; i < teacherDataList.size(); i++) {
            sql.append(",(")
                    .append(teacherDataList.get(i).getXM()).append("',")
                    .append(teacherDataList.get(i).getXBM()).append(",'")
                    .append(teacherDataList.get(i).getSFZJH()).append("','")
                    .append(teacherDataList.get(i).getJZGDQZTM()).append("','")
                    .append(teacherDataList.get(i).getGH()).append("','")
                    .append(teacherDataList.get(i).getSZDWBM()).append("','")
                    .append(teacherDataList.get(i).getGW()).append("','")
                    .append(teacherDataList.get(i).getJRZW()).append("','")
                    .append(teacherDataList.get(i).getTSTAMP()).append("','")
                    .append(teacherDataList.get(i).getLXRQ()).append("','")
                    .append(teacherDataList.get(i).getCJGZNY())
                    .append("')");
        }
        System.out.println(sql.toString());
        jdbcTemplate.batchUpdate(sql.toString());
//        try {
//            jdbcTemplate.batchUpdate(sql.toString());
//        } catch (Exception e) {
//            logger.error(e.getMessage(),e);
//        }
    }
    /**
     * @Description: 导入科研信息表
     * @Author: 毛康源
     * @Date: 2022/10/11
     */
    @Override
    @DS("master")
    public void insertPaperOldInPapers(List<PapersOld> papersOldList) {
        if (papersOldList.size() == 0){
            return;
        }
        Logger logger = null;
        StringBuilder sql = new StringBuilder();
        sql.append("insert into papers(papers_id,papers_name,teacher_id,timestamp) values ");
        sql.append("('")
                .append(papersOldList.get(0).getLWBH()).append("','")
                .append(papersOldList.get(0).getLWTM()).append("','")
                .append(papersOldList.get(0).getDYZZGH()).append("','")
                .append(papersOldList.get(0).getSLSJ()).append("')");
        ;
        for (int i = 1; i < papersOldList.size(); i++) {
            sql.append(",(")
                    .append(papersOldList.get(i).getLWBH()).append("','")
                    .append(papersOldList.get(i).getLWTM()).append("'','")
                    .append(papersOldList.get(i).getDYZZGH()).append("','")
                    .append(papersOldList.get(i).getSLSJ()).append("')");
        }
        System.out.println(sql.toString());
        jdbcTemplate.batchUpdate(sql.toString());
    }

    @Override
    @DS("master")
    public void insertEduReformDataInEdureform(List<EduReformOld> eduReformDataList) {
        if (eduReformDataList.size() == 0){
            return;
        }
        Logger logger = null;
        StringBuilder sql = new StringBuilder();
        sql.append("insert into educational_reform_project(educational_reform_project_id,educational_reform_project_name,teacher_id,timestamp) values");
        sql.append("('")
                .append(eduReformDataList.get(0).getXMBH()).append("','")
                .append(eduReformDataList.get(0).getXMMC()).append("','")
                .append(eduReformDataList.get(0).getTDRYGH()).append("','")
                .append(eduReformDataList.get(0).getTSTAMP()).append("')");
        ;
        for (int i = 1; i < eduReformDataList.size(); i++) {
            sql.append(",(")
                    .append(eduReformDataList.get(0).getXMBH()).append("','")
                    .append(eduReformDataList.get(0).getXMMC()).append("','")
                    .append(eduReformDataList.get(0).getTDRYGH()).append("','")
                    .append(eduReformDataList.get(0).getTSTAMP()).append("')");
        }
        System.out.println(sql.toString());
        jdbcTemplate.batchUpdate(sql.toString());
    }


    /**
     * @author 明祺奇
     * 启动页
     */
    @Override
    public R startupPage(BigInteger teacherId) {
        LambdaQueryWrapper<Teacher> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Teacher::getId, teacherId);
        if (teacherMapper.selectCount(lambdaQueryWrapper) > 0){
            Teacher teacher = teacherMapper.selectOne(lambdaQueryWrapper);
            Date date = new Date();
            Date startDate = teacher.getAdmissionDate();
            TeacherStartupPageVO teacherVO = new TeacherStartupPageVO();
            teacherVO.setTeacherName(teacher.getTeacherName());
            teacherVO.setDay((date.getTime()-startDate.getTime())/(24 * 60 * 60 * 1000));
            return R.Success(teacherVO);
        } else {
            return R.Failed();
        }
    }

    /**
     * @author 明祺奇
     * 我和重工
     */
    @Override
    public R meAndSchool(BigInteger teacherId) {
        LambdaQueryWrapper<Teacher> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Teacher::getId, teacherId);
        if (teacherMapper.selectCount(lambdaQueryWrapper) > 0){
            Teacher teacher = teacherMapper.selectOne(lambdaQueryWrapper);
            SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            return R.Success(bartDateFormat.format(teacher.getAdmissionDate()));
        } else {
            return R.Failed();
        }
    }

    /**
     * @author 明祺奇
     * 档案信息
     */
    @Override
    public R archivalInformation(BigInteger teacherId) {
        LambdaQueryWrapper<Teacher> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Teacher::getId, teacherId);
        if (teacherMapper.selectCount(lambdaQueryWrapper) > 0){
            Teacher teacher = teacherMapper.selectOne(lambdaQueryWrapper);
            LambdaQueryWrapper<Department> queryWrapper = new LambdaQueryWrapper<>();
            StringBuilder departmentCode = new StringBuilder();
            departmentCode.append("0").append(teacher.getDepartmentCode());
            queryWrapper.eq(Department::getDepartmentCode, departmentCode.toString());
            if (departmentMapper.selectOne(queryWrapper) != null) {
                return R.Success(departmentMapper.selectOne(queryWrapper).getDepartmentName());
            } else {
                return R.Failed();
            }
        } else {
            return R.Failed();
        }
    }
    /**
     * @Description: 根据教师工号和学期id查询论文数和教改数
     * @Param: [scienceDTO]
     * @return: com.cdie.myschool.common.R
     * @Author: 毛康源
     * @Date: 2022/10/11
     */
    @Override
    public R scientificInformation(ScienceDTO scienceDTO){
        LambdaQueryWrapper<Papers> lambdaQueryWrapper=new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(Papers::getTeacherId,scienceDTO.getTeacherId());
        if(papersMapper.selectList(lambdaQueryWrapper).size()>0&&papersMapper.selectList(lambdaQueryWrapper).get(0).getSemesterId()==null){
            List<Papers> papersList=papersMapper.getTimestampListPapers(scienceDTO.getTeacherId());
            List<Integer> list=new ArrayList<>();
            papersList.forEach((i)->{
                com.cdie.myschool.domain.entity.Calendar calendar=papersMapper.getSemesterIdPapers(i.getTimestamp());
                if(calendar==null){
                    Date temp = (Date) i.getTimestamp().clone();
                    list.add(getTimeDate(temp));
                }else {
                    list.add(calendar.getSemesterId());
                }
            });
            for(int i=0;i<papersList.size();i++){
                papersMapper.updateSemeterIdPapers(list.get(i),scienceDTO.getTeacherId(),papersList.get(i).getTimestamp());
            }
            List<EduReform> eduReformList=eduReformMapper.getEduTimeStampList();
            List<Integer> listEdu=new ArrayList<>();
            eduReformList.forEach((i->{
                Calendar calendar=papersMapper.getSemesterIdPapers(i.getTimestamp());
                if(calendar==null){
                    Date temp = (Date) i.getTimestamp().clone();
                    listEdu.add(getTimeDate(temp));
                }else {
                    listEdu.add(calendar.getSemesterId());
                }
            }));
            for(int i=0;i<eduReformList.size();i++){
                eduReformMapper.updateSemeterIdEdu(listEdu.get(i),eduReformList.get(i).getTimestamp());
            }
            return R.Success();
        }else{
            LambdaQueryWrapper<Papers> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper1.and(i ->i.eq(Papers::getTeacherId,scienceDTO.getTeacherId()).eq(Papers::getSemesterId,scienceDTO.getSemesterId()));
            Integer papersTotal = papersMapper.selectCount(lambdaQueryWrapper1);
            int eRProjectTot=0;
            ScienceVO scienceVO = new ScienceVO();
            scienceVO.setPapersTotal(papersTotal);
            List<EduReform> eduReformList=eduReformMapper.getEduTeacherIds();
            for(EduReform i : eduReformList){
                eRProjectTot += ThroughMatch(i.getTeacherId(),scienceDTO.getTeacherId());
            }
            scienceVO.setERProjectTot(eRProjectTot);
            return R.Success(scienceVO);
        }
    }
    public int ThroughMatch(String parent,String child) {
        int count = 0;
        //Compile takes substrings as parameters
        Pattern p = Pattern.compile(child);
        //Matcher receives the parent string as a parameter
        Matcher m = p.matcher(parent);
        while (m.find()) {
            count++;
        }
        return count;
    }
    public Integer getTimeDate(Date Timestamp1){
        Integer temp =papersMapper.getSeIdsPapers(Timestamp1);
        if(temp!=null){
            return temp;
        }
        Timestamp1.setTime(Timestamp1.getTime()+(long)27 * 24 * 60 * 60 * 1000);
        return getTimeDate(Timestamp1);
    }
    /**
     * @Description: 导入能力标签表
     * @Param: [scienceDTO]
     * @return: com.cdie.myschool.common.R
     * @Author: 毛康源
     * @Date: 2022/10/12
     */
    @Override
    public R competencyLabel(ScienceDTO scienceDTO) {
        if(abilityTagMapper.getAbilityNo().size()>0&&abilityTagMapper.getAbilityNo()!=null){
            LambdaQueryWrapper<Teacher> lambdaQueryWrapper=new LambdaQueryWrapper();
            lambdaQueryWrapper.eq(Teacher::getTeacherCode,scienceDTO.getTeacherId());
            List<Teacher> teachers=teacherMapper.selectList(lambdaQueryWrapper);

            LambdaQueryWrapper<Papers> lambdaQueryWrapper1=new LambdaQueryWrapper();
            lambdaQueryWrapper1.and(i->i.eq(Papers::getTeacherId,scienceDTO.getTeacherId()).eq(Papers::getSemesterId,scienceDTO.getSemesterId()));
            Integer sciences=papersMapper.selectCount(lambdaQueryWrapper1);

            Integer abilityTagVOS=abilityTagMapper.getCources(scienceDTO.getTeacherId(),scienceDTO.getSemesterId());

            AbilityTagVO abilityTagVO=new AbilityTagVO();
            abilityTagVO.setTeacherName(teachers.get(0).getTeacherName());
            abilityTagVO.setTeacherJob(teachers.get(0).getTeacherJob());
            abilityTagVO.setSciences(sciences);
            abilityTagVO.setCources(abilityTagVOS);
            abilityTagMapper.updateAbilityTag1("良师益友",scienceDTO.getTeacherId());
            if(sciences>=2){
                abilityTagMapper.updateAbilityTag("科研达人",scienceDTO.getTeacherId(),scienceDTO.getSemesterId());
                abilityTagVO.setAbilityTagName("科研达人");
                return R.Success(abilityTagVO);
            }else if (abilityTagVOS>=2){
                abilityTagMapper.updateAbilityTag("教学能手",scienceDTO.getTeacherId(),scienceDTO.getSemesterId());
                abilityTagVO.setAbilityTagName("教学能手");
                return R.Success(abilityTagVO);
            }else{
                abilityTagMapper.updateAbilityTag1("良师益友",scienceDTO.getTeacherId());
                abilityTagVO.setAbilityTagName("良师益友");
                return R.Success(abilityTagVO);
            }
        }else if(abilityTagMapper.getTimetable(scienceDTO.getTeacherId()).size()>0){
            for (AbilityTag i:abilityTagMapper.getTimetable(scienceDTO.getTeacherId())){
                abilityTagMapper.insertAbility(i.getTeacherId(),i.getSemesterId(),i.getTimestamp());
            }
            return R.Success("插入成功");
        }else {
            return R.Success();
        }
    }
}
